package com.example.coapdemo.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;

import java.io.IOException;

public class CborUtil {

    private static ObjectMapper mapper = new ObjectMapper(new CBORFactory());


    /**
     * 将字节数组转换为对象
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T convertObjFromBytes(byte[] data, Class<T> clazz) {
        try {
            return mapper.readValue(data, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 对象转换为字节数组
     */
    public static byte[] convertBytesFromObj(Object obj) {
        try {
            return mapper.writeValueAsBytes(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
